package http_proxy_middleware

import (
	"fmt"
	"strings"

	"gin-gateway/middleware"
	"gin-gateway/core/utils"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

// HTTPWhiteAndBlackListMiddleware 白名单
func HTTPWhiteAndBlackListMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceDetail := GetServiceDetail(c)

		var ipBlackList []string
		if serviceDetail.AccessControl.BlackList != "" {
			ipBlackList = strings.Split(serviceDetail.AccessControl.BlackList, ",")
		}
		if serviceDetail.AccessControl.OpenAuth == 1 && len(ipBlackList) > 0 && utils.StrInSlice(ipBlackList, c.ClientIP()) { // OpenAuth 开启白/黑名单权限
			middleware.ResponseError(c, 3001, errors.New(fmt.Sprintf("%s in ip black list", c.ClientIP())))
			c.Abort()
			return
		}

		var ipWhiteList []string
		if serviceDetail.AccessControl.WhiteList != "" {
			ipWhiteList = strings.Split(serviceDetail.AccessControl.WhiteList, ",")
		}
		if serviceDetail.AccessControl.OpenAuth == 1 && len(ipWhiteList) > 0 && !utils.StrInWhileList(ipWhiteList, c.ClientIP()) { // 是否在白名单
			middleware.ResponseError(c, 3001, errors.New(fmt.Sprintf("%s not in ip white list", c.ClientIP())))
			c.Abort()
			return
		}
		c.Next()
	}
}
